using AutoMapper;
using Com.Ctrip.Framework.Apollo;
using Consul;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Primitives;
using Repository.communal;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.Elasticsearch;
using SqlSugar;
using System.Reflection;
using Warehouse.API;
using Warehouse.Repository;
using Warehouse.Services.IServices;
using Warehouse.Services.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
//Program中 elk
var configuration = builder.Configuration;
// 配置Serilog
var elaUri = configuration["ELK:ElaticSearchUrl"];
var userName = configuration["ELK:UserName"];
var password = configuration["ELK:Password"];
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithThreadId()
.Enrich.WithProcessId()
.WriteTo.Console(new Serilog.Formatting.Compact.CompactJsonFormatter())
.WriteTo.File("logs/warehousewrite-.txt",
rollingInterval: RollingInterval.Day,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(elaUri))
{
    IndexFormat = "warehousewrite-logs-{0:yyyy.MM.dd}",
    AutoRegisterTemplate = true,
    AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
    ModifyConnectionSettings = conn => conn.BasicAuthentication(userName, password),
    BufferBaseFilename = "./logs/serilog-buffer",
    Period = TimeSpan.FromSeconds(2)
})
.CreateLogger();
builder.Host.UseSerilog();
//consul
static void RegisterConsul()
{
    try
    {
        var consulClient = new ConsulClient(p => {
            p.Address = new Uri("http://115.190.167.248:8500");//主机ip:8500
        });
        // 2. 确保健康检查端点可访问
        var httpCheck = new AgentServiceCheck()
        {
            DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
            Interval = TimeSpan.FromSeconds(10),
            HTTP = "http://114.132.166.218:7012/WeatherForecast", // 确认此端口服务是否运行,WeatherForecast是天气预报控制器，如果没有这个控制器可以手动创建一个
            Timeout = TimeSpan.FromSeconds(5)
        };
        // 3. 添加标签方便识别
        var registration = new AgentServiceRegistration()
        {
            Checks = new[] { httpCheck },
            ID = $"warehousewrite-{Guid.NewGuid()}", // 更易读的ID
            Name = "warehousewrite",                // 业务api名称,必须小写
            Address = "115.190.167.248",                   // 纯IP正确
            Port = 7011,                               // 端口与健康检查一致
            Tags = new[] { "dotnet-service" }           // 添加标签
        };

        // 4. 添加错误处理
        var result = consulClient.Agent.ServiceRegister(registration).Result;
        Console.WriteLine($"服务注册成功! Status: {result.StatusCode}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Consul注册失败: {ex.Message}");
    }
}
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Configuration.AddApollo(builder.Configuration.GetSection("Apollo")).AddDefault().AddNamespace("systemread");

builder.Services.AddDbContext<MyDbContext>(options =>
              options.UseMySql(
                  builder.Configuration.GetValue<string>("warehouse"),
                  new MySqlServerVersion(new Version(9, 4)) // ָ�� MySQL �汾
              )
          );
// 注册 SqlSugar
builder.Services.AddScoped<ISqlSugarClient>(provider =>
{
    var connectionString = builder.Configuration.GetValue<string>("warehouse");

    return new SqlSugarClient(new ConnectionConfig()
    {
        ConnectionString = connectionString,
        DbType = DbType.MySql,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute
    });
});

// 注册库存事务相关服务
builder.Services.AddScoped<IInventoryTransactionRepository, InventoryTransactionRepository>();
builder.Services.AddScoped<IInventoryTransactionService, InventoryTransactionService>();

// 注册调拨单相关服务
builder.Services.AddScoped<IAllocationRepository, AllocationRepository>();
builder.Services.AddScoped<Warehouse.Services.IServices.IAllocationService, Warehouse.Services.Services.AllocationService>();

builder.Services.AddMediatR(cfg => {
    cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
});

// 注册 HttpClient 工厂，用于写侧通知读侧
builder.Services.AddHttpClient();
var app = builder.Build();
RegisterConsul();

// Configure the HTTP request pipeline.
if (app.Configuration is IConfigurationRoot configurationRoot)
{
    ChangeToken.OnChange(
        () => configurationRoot.GetReloadToken(),
        () => Console.WriteLine($"配置已更新:{app.Configuration.GetValue<string>("warehouse")}"));
}

app.UseSwagger();
app.UseSwaggerUI();
app.UseCors(x=>x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseAuthorization();

app.MapControllers();

app.Run();
